package com.three.service.impl;

import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.three.dao.ClazzDao;
import com.three.dao.CrollcallDao;
import com.three.dao.SRrecordDao;
import com.three.dao.SrollcallDao;
import com.three.dao.UserDao;
import com.three.entity.Crollcall;
import com.three.entity.User;
import com.three.service.CrollcallService;
import com.three.util.Constant;
import com.three.util.GenCodes;

@Service
public class CrollcallServiceImpl implements CrollcallService {

	@Autowired
	CrollcallDao crollcallDao;
	@Autowired
	SrollcallDao srollcallDao;
	@Autowired
	ClazzDao clazzDao;
	@Autowired
	UserDao userDao;
	@Autowired
	SRrecordDao sRrecordDao;

	@Override
	public List<Crollcall> findCrollcallsByCid(Integer cid) {
		return crollcallDao.findCrollcallsByCid(cid);
	}

	/**
	 * 创建考勤
	 * 如果人数为0 返回"failed"
	 * 如果人数不为0 更新clazz表考勤码
	 * 			  c_rollcall插入一条新的班级考勤信息
	 * 			   返回crollcallId+","+rollcallCode+","+班级人数
	 */
	@Override
	public String createCrollcalls(Integer cid, String name, String date) {
		String result= null;
		//获取班级学生人数，如果班级学生人数为0，则返回"failed"
		List<User> users = userDao.findStudentsByCid(cid);
		int num = users.size();
		if (num > 0) {			
			String rollcallCode = GenCodes.genFourNumberCodes();
			clazzDao.updateRollcallCode(rollcallCode, cid);
			crollcallDao.addCrollcall(cid, name, date);
			int crollcallId = crollcallDao.findLastInsertId();
			result = crollcallId+","+rollcallCode+","+num;
			SimpleDateFormat sdf = new SimpleDateFormat();
			for (int i = 0; i < users.size(); i++) {
				List<Integer> ucids = clazzDao.findUcidByUidWithCid(
						users.get(i).getId(), cid);
				int ucid = ucids.get(0);
				sRrecordDao.addSRrecord(ucid, date, Constant.MISS);
				srollcallDao.updateMiss(ucid, 
						srollcallDao.findMissByUcid(ucid)+1);
			}
		}else {
			result="failed";
		}
		return result;
	}

	@Override
	public String stopRollcall(Integer cid, String rollcallName,
			Integer attendance, Integer miss) {
		String result = null;
		//向c_rollcall中添加数据
		crollcallDao.updateCrollcallStates(cid, rollcallName, attendance, miss);
		//把clazz中rollcallCode更新为"stopped"
		clazzDao.updateRollcallCode("stopped", cid);
		result = "success";
		return result;
	}
	
	

}
